﻿using System;
using System.Collections.Concurrent;

namespace Ue.Infrastructure.Caching
{
    public class CacheHolder : ICacheHolder
    {
        private readonly ICacheContextAccessor cacheContextAccessor;
        private readonly ConcurrentDictionary<CacheKey, object> caches = new ConcurrentDictionary<CacheKey, object>();

        public CacheHolder(ICacheContextAccessor cacheContextAccessor) {
            this.cacheContextAccessor = cacheContextAccessor;
        }

        #region ICacheHolder 成员

        public ICache<TKey, TResult> GetCache<TKey, TResult>(Type component)
        {
            var cacheKey = new CacheKey(component, typeof(TKey), typeof(TResult));
            var result = this.caches.GetOrAdd(cacheKey, k => new Cache<TKey, TResult>(this.cacheContextAccessor));
            return (Cache<TKey, TResult>)result;
        }

        #endregion

        class CacheKey : Tuple<Type, Type, Type>
        {
            public CacheKey(Type component, Type key, Type result)
                : base(component, key, result) { }
        }
    }
}
